import { useRef, useEffect, useState } from "react";

import { TranscriberData } from "../hooks/useTranscriber";
import { formatAudioTimestamp } from "../utils/AudioUtils";
import axios from "axios";
interface Props {
    transcribedData: TranscriberData | undefined;
}

export default function Transcript({ transcribedData }: Props) {
    const divRef = useRef<HTMLDivElement>(null);
    const [translations, setTranslations] = useState<{ [key: string]: any }>({});
    const [translatedTexts, setTranslatedTexts] = useState<Set<string>>(new Set());
   // const [processedTimestamps, setProcessedTimestamps] = useState<Set<number>>(new Set());
    const saveBlob = (blob: Blob, filename: string) => {
        const url = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = filename;
        link.click();
        URL.revokeObjectURL(url);
    };
    const exportTXT = () => {
        let chunks = transcribedData?.chunks ?? [];
        let text = chunks
            .map((chunk) => chunk.text)
            .join("")
            .trim();
        console.log(text);
        const blob = new Blob([text], { type: "text/plain" });

        saveBlob(blob, "transcript.txt");
    };
    const exportJSON = () => {
        let jsonData = JSON.stringify(transcribedData?.chunks ?? [], null, 2);

        // post-process the JSON to make it more readable
        const regex = /(    "timestamp": )\[\s+(\S+)\s+(\S+)\s+\]/gm;
        jsonData = jsonData.replace(regex, "$1[$2 $3]");

        const blob = new Blob([jsonData], { type: "application/json" });
        saveBlob(blob, "transcript.json");
    };

    // Scroll to the bottom when the component updates
    useEffect(() => {
        if (divRef.current) {
            const diff = Math.abs(
                divRef.current.offsetHeight +
                divRef.current.scrollTop -
                divRef.current.scrollHeight,
            );

            if (diff <= 64) {
                // We're close enough to the bottom, so scroll to the bottom
                divRef.current.scrollTop = divRef.current.scrollHeight;
            }
        }
    });
        // 新增：翻译请求函数
    const translateText = async (text: string) => {
        //try {
        // const response = await fetch("/translate/hellopost", {
        //     method: "POST",
        //     headers: {
        //         "Content-Type": "application/json",
        //     },
        //     body: JSON.stringify({ content: text }),
        // });

        // if (!response.ok) {
        //     console.error("Translation request failed:", response.statusText);
        // } else {
        //     console.log(response);
        //     const result = await response.json();
        //     console.log("Translation result:", result);

        const response = await axios.post("/translate/hellopost", {
            content: text,
        }, {
            headers: {
                "Content-Type": "application/json",
            },
        });
        // 处理响应数据
        console.log("Translation result:", response);

         // 判断响应是否有效
    if (response.status !== 200 || !response.data) {
      console.warn("Translation failed or returned empty result:", text);
      return; // 跳过无效结果
    }
        const result = response.data;
        // 使用 chunk.text 作为 key 存储翻译结果
        setTranslations((prev) => ({
            ...prev,
            [text.trim()]: result || "No translation",
        }));

    };
    useEffect(() => {
        console.log(transcribedData);
        if (!transcribedData?.chunks || transcribedData.chunks.length === 0) return;

        const lastChunk = transcribedData.chunks[transcribedData.chunks.length - 1];
        const text = lastChunk.text;
         //const timestamp = lastChunk.timestamp?.[0]; // 获取时间戳起点

        if (text && text.length > 4 && !translatedTexts.has(text)  &&transcribedData.isBusy==false) {
           // translateText(text);
            //setTranslatedTexts((prev) => new Set(prev).add(text));
             translateText(transcribedData.text);
            setTranslatedTexts((prev) => new Set(prev).add(transcribedData.text));
           // setProcessedTimestamps((prev) => new Set(prev).add(timestamp)); // 标记该时间戳已处理
        }
    }, [transcribedData?.chunks]);
    return (
        <div
            ref={divRef}
            className='w-full flex flex-col my-2 p-4 max-h-[20rem] overflow-y-auto'
        >
            {transcribedData?.chunks &&
                transcribedData.chunks.map((chunk, i) => (

                    <div
                        key={`${i}-${chunk.text}`}
                        className='w-full flex flex-row mb-2 bg-white rounded-lg p-4 shadow-xl shadow-black/5 ring-1 ring-slate-700/10'
                    >
                        <div className='mr-5'>
                            {formatAudioTimestamp(chunk.timestamp[0])}
                        </div>
                        {chunk.text}
                    </div>
                )
                )
            }
            {/* {transcribedData?.chunks &&
                transcribedData.chunks.map((chunk, i) => {
                    //     let temptranslateText=transcribedData.chunks[i]?.text;
                    //  //   console.log(transcribedData.chunks[i]);
                    //     if (transcribedData.chunks[i]?.text==chunk.text) {
                    //      translateText(chunk.text);
                    //     }
                    return (
                        <div
                            key={`${i}-${chunk.text}`}
                            className='w-full flex flex-row mb-2 bg-white rounded-lg p-4 shadow-xl shadow-black/5 ring-1 ring-slate-700/10'
                        >
                            <div className='mr-5'>
                                翻译{formatAudioTimestamp(chunk.timestamp[0])}
                            </div>
                            <div className='text-right ml-auto'>
                              
                                {chunk.text.trim() in translations ? (
                                    <div className="text-blue-600">{translations[chunk.text.trim()]}</div>
                                ) : (
                                    <div>Translating...</div>
                                )}
                            </div> 
                        </div>
                    );
                }
                )
            } */}
            {!transcribedData?.isBusy && transcribedData?.text && (
    <div className="w-full flex flex-row mb-2 bg-white rounded-lg p-4 shadow-xl shadow-black/5 ring-1 ring-slate-700/10">
        <div className="mr-5">
            总翻译
        </div>
        <div className="text-right ml-auto">
            {/* 显示翻译结果 */}
            {transcribedData.text.trim() in translations ? (
                <div className="text-blue-600">{translations[transcribedData.text.trim()]}</div>
            ) : (
                <div>Translating...</div>
            )}
        </div>
    </div>
)}
           {/* {transcribedData?.chunks &&transcribedData?.isBusy===false &&
                transcribedData.chunks.map((chunk, i) => {
                   
                    return ( 
                        <div
                            key={`${i}-${chunk.text}`}
                            className='w-full flex flex-row mb-2 bg-white rounded-lg p-4 shadow-xl shadow-black/5 ring-1 ring-slate-700/10'
                        >
                            <div className='mr-5'>
                                翻译{formatAudioTimestamp(chunk.timestamp[0])}
                            </div>
                            <div className='text-right ml-auto'>
                            
                                {transcribedData.text.trim() in translations ? (
                                    <div className="text-blue-600">{translations[transcribedData.text.trim()]}</div>
                                ) : (
                                    <div>Translating...</div>
                                )}
                            </div> 
                        </div>
                    );
                }
                )
            } */}
            {/* {transcribedData && !transcribedData.isBusy && (
                <div className='w-full text-right'>
                    <button
                        onClick={exportTXT}
                        className='text-white bg-green-500 hover:bg-green-600 focus:ring-4 focus:ring-green-300 font-medium rounded-lg text-sm px-4 py-2 text-center mr-2 dark:bg-green-600 dark:hover:bg-green-700 dark:focus:ring-green-800 inline-flex items-center'
                    >
                        Export TXT
                    </button>
                    <button
                        onClick={exportJSON}
                        className='text-white bg-green-500 hover:bg-green-600 focus:ring-4 focus:ring-green-300 font-medium rounded-lg text-sm px-4 py-2 text-center mr-2 dark:bg-green-600 dark:hover:bg-green-700 dark:focus:ring-green-800 inline-flex items-center'
                    >
                        Export JSON
                    </button>
                </div>
            )} */}
        </div>
    );
}
